package com.jstyle.jclife.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jstyle.countrylibrary.CountryPage;
import com.jstyle.jclife.NetWork.NetWorkException;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.BindDeviceActivity;
import com.jstyle.jclife.activity.FindPasswordActivity;
import com.jstyle.jclife.activity.MainActivity;
import com.jstyle.jclife.activity.RegisterActivity;
import com.jstyle.jclife.activity.UserInfoSettingActivity;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.ActionData;
import com.jstyle.jclife.model.BindDeviceInfo;
import com.jstyle.jclife.model.NetResultData;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.model.UserInfoQuery;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.RxBus;
import com.jstyle.jclife.utils.SHA1;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.ShareTools;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.EditTextWithDelete;
import com.mob.tools.FakeActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


/**
 * 登录
 */
public class LoginFragment extends BaseFragment {
    private static final String TAG = "LoginFragment";

    @BindView(R.id.et_login_phonenumber)
    EditTextWithDelete etLoginPhonenumber;
    @BindView(R.id.et_login_password)
    EditTextWithDelete etLoginPassword;
    @BindView(R.id.tv_login_forgetpassword)
    TextView tvLoginForgetpassword;
    @BindView(R.id.bt_login_login)
    Button btLoginLogin;


    ShareTools shareTools;
    String token;
    @BindView(R.id.tv_to_register)
    TextView tvToRegister;
    @BindView(R.id.bt_login_wechat)
    ImageView btLoginWechat;
    @BindView(R.id.bt_login_facebook)
    ImageView btLoginFacebook;
    @BindView(R.id.bt_login_twitter)
    ImageView btLoginTwitter;
    @BindView(R.id.RadioButton_sign_phone)
    RadioButton RadioButtonSignPhone;
    @BindView(R.id.RadioButton_sign_email)
    RadioButton RadioButtonSignEmail;
    @BindView(R.id.RadioGroup_loginAccount)
    RadioGroup RadioGroupLoginAccount;


    //    @BindView(R.id.rb_login_phone)
//    RadioButton rbLoginPhone;
//    @BindView(R.id.rb_login_email)
//    RadioButton rbLoginEmail;
//    @BindView(R.id.RadioGroup_loginAccount)
//    RadioGroup RadioGroupLoginAccount;
    private String countryCode = "001-";

    @BindView(R.id.bt_login_getCountryCode)
    Button btLoginGetCountryCode;
    private String language = "zh";
    private Disposable subscription;


    private void saveUserInfo(String id) {
        uid = id;
        String phone = etLoginPhonenumber.getText().toString();
        String psd = etLoginPassword.getText().toString();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(id);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(id);
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);
            UserInfoDaoManager.insertUser(userInfo);
        } else {
            userInfo.setUserId(id);
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);
            UserInfoDaoManager.updateUser(userInfo);
        }
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_REMIND_PSD, checkboxLogin.isChecked());
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, true);
        //  if (!checkboxLogin.isChecked()) return;
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_account_type, isPhoneAccount);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_AUTH_USERID, "");
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PHONE, phone);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PSD, psd);
    }


    @BindView(R.id.checkbox_login)
    CheckBox checkboxLogin;
    boolean isPhoneAccount = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        ButterKnife.bind(this, view);

        initView();
        // shareTools = new ShareTools(this);
        //   shareTools.setShareListener(this);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    private void initView() {
        tvToRegister.setText(Html.fromHtml(getString(R.string.register_link)));
        Locale locale = getResources().getConfiguration().locale;
        language = locale.getLanguage();
        //llLogin2.setVisibility(language.equals("zh") ? View.GONE : View.VISIBLE);
        //llLogin1.setVisibility(language.equals("zh") ? View.VISIBLE : View.GONE);
        boolean isRemind = SharedPreferenceUtils.getSpBoolean(SharedPreferenceUtils.KEY_REMIND_PSD);

        isPhoneAccount = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_account_type,
                "zh".equals(language));

        if (isPhoneAccount) {
            RadioButtonSignPhone.setChecked(true);
        } else {
            RadioButtonSignEmail.setChecked(true);
        }
        switchAccountType(isPhoneAccount);

        showUserInfo();
        if (isRemind) {
            checkboxLogin.setChecked(true);
        }
        checkboxLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            }
        });

        RadioGroupLoginAccount.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.RadioButton_sign_phone:
                        isPhoneAccount = true;
                        break;
                    case R.id.RadioButton_sign_email:
                        isPhoneAccount = false;
                        break;
                }
                switchAccountType(isPhoneAccount);
            }
        });
        subscription = RxBus.getInstance().toObservable(ActionData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ActionData>() {
            @Override
            public void accept(ActionData data) throws Exception {
                String action = data.getAction();
                if (ActionData.FinishSignIn.equals(action)) {
                    showUserInfo();
                    login();
                }
            }
        });
    }

    private void changeUserAccount() {

    }

    private void showUserInfo() {

        countryCode = SharedPreferenceUtils.getString(SharedPreferenceUtils.KEY_countryCode, getString(R.string.DefaultCountryCode));
        btLoginGetCountryCode.setText("+" + countryCode.split("-")[0].replace("0", ""));

        //RadioGroupLoginAccount.check(isPhoneAccount?R.id.rb_login_phone:R.id.rb_login_email);
        String phone = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_PHONE);
        String psd = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_PSD);
        if (!TextUtils.isEmpty(phone)) etLoginPhonenumber.setText(phone);
        if (!TextUtils.isEmpty(psd)) etLoginPassword.setText(psd);
    }


    @OnClick({R.id.tv_to_register, R.id.bt_login_getCountryCode, R.id.tv_login_forgetpassword, R.id.bt_login_login,
    })
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.tv_to_register:
                startActivity(RegisterActivity.class);
                break;
            case R.id.tv_login_forgetpassword:
                startActivity(FindPasswordActivity.class);
                break;
            case R.id.bt_login_login:
                login();
                break;
            case R.id.bt_login_getCountryCode:
                getCountryCode();
                break;
        }
    }

    private void getCountryCode() {
        CountryPage phone = new CountryPage();
        phone.setCountryId("1");
        phone.showForResult(getActivity(), (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                String currentId = (String) data.get("id");
                int result = (int) data.get("result");
                if (result == CountryPage.Result_OK) {
                    String[] res = SMSSDK.getCountry(currentId);
                    btLoginGetCountryCode.setText("+" + res[1]);
                    countryCode = "00" + res[1] + "-";
                }
            }
        });
    }

    private void login() {
        if (!NetWorkUtil.isNetworkConnected(getContext())) {
            showToast(getResources().getString(R.string.Network_not_availa));
            return;
        }
        Log.i(TAG, "login: " + language);
        Locale locale = getResources().getConfiguration().locale;
        Log.i(TAG, "login: " + locale.getLanguage());
        String account = etLoginPhonenumber.getText().toString();
        String password = etLoginPassword.getText().toString();
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(account)) {
            showToast(getString(R.string.login_input_all));
            return;
        }
        Map<String, Object> map = new HashMap<>();

        if (isPhoneAccount) {
            map.put(NetWorkConast.KEY_PHONE, countryCode + account);
        } else {
            map.put(NetWorkConast.KEY_userEmail, account);
        }
        map.put(NetWorkConast.KEY_userpwd, password.length() == 32 ? password : SHA1.md5Encoder(password));
        NetWorkUtil.addSHA1(map);
        showProgressDialog(getString(R.string.login_logining));
        NetWorkUtil.getInstance()
                .getJstyleApi()
                .login(map)
                .flatMap(new Function<NetResultData<String>, ObservableSource<NetResultData<UserInfoQuery>>>() {
                    @Override
                    public ObservableSource<NetResultData<UserInfoQuery>> apply(NetResultData<String> netResultData) throws Exception {
                        int msgCode = netResultData.getMsgCode();
                        String msg = NetWorkConast.getResult(msgCode, getContext());
                        if (msgCode == NetResultData.Success_Code) {
                            saveUserInfo(netResultData.getData());
                            return NetWorkUtil.getInstance()
                                    .getJstyleApi()
                                    .getUserInfo(netResultData.getData());
                        } else {
                            throw new NetWorkException(msg);
                        }
                    }
                })
                .compose(SchedulersTransformer.<NetResultData<UserInfoQuery>>io2MainObservable())
                .subscribe(new Observer<NetResultData<UserInfoQuery>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NetResultData<UserInfoQuery> value) {
                        disMissProgressDialog();
                        int msgCode = value.getMsgCode();
                        String msg = NetWorkConast.getResult(msgCode, getContext());
                        if (msgCode == NetResultData.Success_Code) {
                            SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, true);
                            boolean isFirst = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_Is_First, true);
                            if (value.getData() != null) {
                                updateUserInfo(value.getData());
                            }
//                            if(BuildConfig.APPLICATION_ID.equals("com.jstyle.fomofit")){
//                                startActivity(isFirst ? BindDeviceActivity.class : MainActivity.class);
//                            }else {
                            startActivity();
                            getActivity().finish();
                            return;
                        } else if (msgCode == NetResultData.Failed_Code) {
                            msg = getResources().getString(R.string.login_loginfailed);
                        }
                        showToast(msg);

                    }

                    @Override
                    public void onError(Throwable e) {
                        disMissProgressDialog();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    String uid;

    private void startActivity() {
        boolean isFirst = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_Is_First, true);
        Class next = null;
        if (isFirst) {
            next = BindDeviceActivity.class;
        } else {
            List<BindDeviceInfo> bindDeviceInfoList = BindDeviceInfoDaoManager.queryAllData();
            if (bindDeviceInfoList.size() != 0) {
                UserInfo userInfo = UserInfoDaoManager.getUserByUid(uid + "");
                String iconPath = userInfo.getIconPath();
                next = TextUtils.isEmpty(iconPath) ? UserInfoSettingActivity.class : MainActivity.class;
            } else {
                next = BindDeviceActivity.class;
            }
        }
        startActivity(next, SharedPreferenceUtils.KEY_From_Login, true);

    }

    private void updateUserInfo(UserInfoQuery data) {

        UserInfo userInfo = UserInfoDaoManager.getUserByUid(data.getUid() + "");
        int age = 25;
        if (!TextUtils.isEmpty(data.getBirthday())) {
            String[] birthdayArray = data.getBirthday().split("-");
            int year = Integer.parseInt(birthdayArray[0]);
            Calendar calendar = Calendar.getInstance();
            int nowYear = calendar.get(Calendar.YEAR);
            age = nowYear - year;
        }

        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(data.getUid() + "");
            userInfo.setAge(age);
            userInfo.setBirthday(data.getBirthday());
            userInfo.setHeight(data.getStature());
            if (!TextUtils.isEmpty(data.getAvatar())) userInfo.setIconPath(data.getAvatar());
            userInfo.setName(data.getNikeName());
            userInfo.setWeight(data.getWeight());
            userInfo.setGender(data.getGender().equals("male") ? 0 : 1);
            UserInfoDaoManager.insertUser(userInfo);
        } else {
            userInfo.setUserId(data.getUid() + "");
            userInfo.setAge(age);
            userInfo.setBirthday(data.getBirthday());
            userInfo.setHeight(data.getStature());
            userInfo.setName(data.getNikeName());
            userInfo.setWeight(data.getWeight());
            if (!TextUtils.isEmpty(data.getAvatar())) userInfo.setIconPath(data.getAvatar());
            if (TextUtils.isEmpty(data.getGender())) {
                userInfo.setGender(0);
            } else {
                userInfo.setGender(data.getGender().equals("male") ? 0 : 1);
            }

            UserInfoDaoManager.updateUser(userInfo);
        }
        saveUserIcon(data.getAvatar());
    }

    @Override
    public void switchAccountType(boolean isPhoneAccount) {
        super.switchAccountType(isPhoneAccount);
        etLoginPassword.setText("");
        etLoginPhonenumber.setText("");
        etLoginPhonenumber.setHint(isPhoneAccount ? R.string.login_input_phone : R.string.login_input_email);
        btLoginGetCountryCode.setVisibility(isPhoneAccount ? View.VISIBLE : View.GONE);
    }

    //    @Override
//    public void ShareSuccess(String userName, String headUrl, String platName, String userId) {
//
//        getAuthUserInfo(userName, headUrl, platName, userId);
//        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_NICKNAME, userName);
//
//    }

    private void saveUserIcon(String headUrl) {
        if (TextUtils.isEmpty(headUrl)) return;
        NetWorkUtil.getInstance().getJstyleApi().downloadIcon(headUrl).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody value) {

                        try {
                            writeToDisk(value);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {


                    }
                });
    }

    private void writeToDisk(ResponseBody responseBody) throws IOException {
        File file = new File(ImageUtils.headPath);
        File fileIcon = new File(ImageUtils.headPath + ImageUtils.md5Encoder(NetWorkUtil.getUserId()));
        Log.i(TAG, "writeToDisk: " + ImageUtils.md5Encoder(NetWorkUtil.getUserId()));
        if (!file.exists()) {
            file.mkdirs();
        }
        if (fileIcon.exists() && fileIcon.length() == responseBody.contentLength()) {
            // finishLogin();
            return;
        }
      try{
          byte[] buffer = new byte[1024 * 8];
          int len;
          FileOutputStream out = new FileOutputStream(fileIcon);
          InputStream in = responseBody.byteStream();
          while ((len = in.read(buffer)) != -1) {
              out.write(buffer, 0, len);
          }
          out.flush();
          out.close();
          in.close();
      }catch (FileNotFoundException E){E.printStackTrace();}
        //  finishLogin();
    }


//    @Override
//    public void ShareFailed() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                showToast(getString(R.string.login_loginfailed));
//            }
//        });
//    }

//    @Override
//    public void shareCancel() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                showToast(getString(R.string.login_third_usercancel));
//            }
//        });
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unSubscribe(subscription);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
